import requests
import json

app_id = "eb1ea6cf-01b7-42ec-9a22-268f4c837407"
beaver = 'Bearer bce-v3/ALTAK-XLQmAG5r8mpiwISMu9Cvq/095fd83e6a06ac73f05aee2bee6ec38af1f190d3'

# 新建一个会话，打招呼
url = "https://qianfan.baidubce.com/v2/app/conversation"

payload = json.dumps({
    "app_id": app_id
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': beaver
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
conversation_id = json.loads(response.text)['conversation_id']

# 2.（可选，对话时上传文件使用），获取file_id
print("输出的会话id为：" + conversation_id)
url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"

payload = {
    'app_id': app_id,
    'conversation_id': conversation_id
}
files = [
    ('file', ('1.png', open(r'1.png', 'rb'), 'image/jpeg'))
]
headers = {
    'X-Appbuilder-Authorization': beaver
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)
response_data = json.loads(response.text)
file_id = response_data.get("id")  # 提取file_id，而不是使用内置的id函数
print("上传的文件ID为：", file_id)

# 2.问答请求
url = "https://qianfan.baidubce.com/v2/app/conversation/runs"

query = input("请输入问题：")
payload = json.dumps({
    "app_id": app_id,
    "query": query,
    "stream": False,
    "conversation_id": conversation_id,
    "file_ids": [
        file_id
    ]
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': beaver
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
# todo-1：只打印answer
result = json.loads(response.text)["answer"]
#
# todo-2：将问题答案存入txt
with open('./answer.txt', 'a',encoding='utf8') as f:
    f.write(result + '\n')
